/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bff.slimserver.musicjukebox.ui.components.favorites;

import com.bff.slimserver.musicjukebox.lib.JukeboxProperties;
import com.bff.slimserver.musicjukebox.lib.actions.AddFavoriteAction;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import org.bff.slimserver.exception.SlimException;
import org.bff.slimserver.musicobjects.SlimObject;
import org.bff.slimserver.musicobjects.SlimPlayableObject;

/**
 *
 * @author bfindeisen
 */
public class FavoritesAddButton extends JButton {

    private String favURL;
    private boolean checked;

    public FavoritesAddButton(String year) {
        setYear(year);
        setUI();      
    }

    public FavoritesAddButton(SlimPlayableObject object) {
        setObject(object);
        setUI();
    }

    private void setUI() {
        setFont(new java.awt.Font("Tahoma", 0, 10));
        setText(null);
        setContentAreaFilled(false);
        Dimension dim = new Dimension(16, 16);
        setPreferredSize(dim);
        setMinimumSize(dim);
        setMaximumSize(dim);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        if (!isChecked()) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    if (!isChecked() && favURL != null) {
                        checkFavorite();
                        setChecked(true);
                    }
                }
            }).start();
        }
    }

    private void checkFavorite() {
        try {
            if (JukeboxProperties.getInstance().getFavoritesPlugin().isFavorite(favURL)) {
                ((AddFavoriteAction) getAction()).setExistsIcon();
            } else {
                ((AddFavoriteAction) getAction()).setNormalIcon();
            }
        } catch (SlimException ex) {
            Logger.getLogger(FavoritesAddButton.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @return the checked
     */
    public boolean isChecked() {
        return checked;
    }

    /**
     * @param checked the checked to set
     */
    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    public void setYear(String year) {
        setAction(new AddFavoriteAction(year));

        if (year != null) {
            this.favURL = SlimObject.URL_PREFIX_YEAR + year;
        }
    }

    public void setObject(SlimPlayableObject object) {
        setAction(new AddFavoriteAction(object));
 
        if (object != null) {
            this.favURL = object.getUrl();
        }
    }

}
